package com.atguigu.lease.web.app.service.impl;


import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.common.utils.VerifyCodeUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.mapper.UserInfoMapper;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.SmsService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jacoco.agent.rt.internal_035b120.core.internal.flow.IFrame;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private SmsService smsService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    UserInfoMapper userInfoMapper;
    @Override
    public void getCode(String phone) {

        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        // 一个手机号  :  1分钟(60s)内只能发送一次短信
        // 已经发过短信, 检验时间
        Boolean result = redisTemplate.hasKey(key);
        if (result){
            Long expireTime = redisTemplate.getExpire(key);
            // 验证码实际有效期
            Integer totalTime = RedisConstant.APP_LOGIN_CODE_TTL_SEC;
            if ((totalTime - expireTime) < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC){
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }


        // 生成验证码
        String code = VerifyCodeUtil.generateCode(6);
        // 发送验证码
        smsService.sendMsg(phone, code);
        // redis保存验证码

//        redisTemplate.opsForValue().set(key, code, RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);
        redisTemplate.opsForValue().set(key, code, RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);
    }

    @Override
    public String login(LoginVo loginVo) {

        String phone = loginVo.getPhone();
        String code = loginVo.getCode();

        if (!StringUtils.hasText(phone)){
            throw new LeaseException((ResultCodeEnum.APP_LOGIN_PHONE_EMPTY));
        }

        if (!StringUtils.hasText(code)){
            throw  new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }

        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        String redisCode = redisTemplate.opsForValue().get(key);

        if (redisCode == null){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }

        if (!redisCode.equals(code)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }

        // 确定mysql数据: 用户是否存在
        /**
         * 如果存在 给前端响应token
         * 如果不存在 自动保存为会员 再响应token信息
         */

        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getPhone, phone));

        if (userInfo == null){
            // 自动保存为会员
            userInfo = new UserInfo();
            userInfo.setPhone(phone);
            userInfo.setNickname("用户-" + phone.substring(7));
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfoMapper.insert(userInfo);
        }else {
            if (userInfo.getStatus() == BaseStatus.DISABLE){
                throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
            }
        }

        // 生成token
        String token = JwtUtil.createToken(userInfo.getId(), phone);
        // 1.
        return token;
    }


}
